﻿using CityGrid.Common.Utilities;
using CQRSFramework.Common.Components;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using CQRSFramework.Commands;

namespace CQRSFramework.Events.Impl
{
    public class DefaultEventProcess : IEventProcess
    {
        private readonly IProcessingEventHandler _handler;
        private ConcurrentDictionary<string, EventMailBox> _dic = new ConcurrentDictionary<string, EventMailBox>();
        public DefaultEventProcess(IProcessingEventHandler handler)
        {
            _handler = handler;
        }

        public void Process(IDomainEvent evnt, IModel _channel, BasicDeliverEventArgs _ea)
        {
            var mailBox = _dic.GetOrAdd(evnt.AggregateRootId, x =>
               {
                   return new EventMailBox(evnt.AggregateRootId, _handler);
               });
            mailBox.Enqueue(new ProcessingEvent() { Channel = _channel, Evnt = evnt, EA = _ea });
        }
    }
}
